package com.ccys.netty.handler;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ccys.common.util.StringUtil;
import com.ccys.netty.config.NettyConfig;
import com.ccys.netty.config.NettyServer;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;


/**
 * TextWebSocketFrame类型， 表示一个文本帧
 * @author sixiaojie
 * @date 2020-03-28-13:47
 */
@Component
@ChannelHandler.Sharable
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static final Logger log = LoggerFactory.getLogger(NettyServer.class);
    public static AtomicInteger nConnection = new AtomicInteger();
    @Override
    public void channelRegistered(ChannelHandlerContext ctx)  {
        log.info("========客户端注册=======");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx)  {
        log.info("========客户端注销=======");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx)  {
        log.info("========客户端连接=======");
        nConnection.incrementAndGet();
        log.info("========当前连接数:{}",nConnection.get());

    }
    @Override
    public void channelInactive(ChannelHandlerContext ctx)  {
        log.info("========客户端断开=======");
        nConnection.decrementAndGet();
    }
    /**
     * 一旦连接，第一个被执行
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        log.info("handlerAdded 被调用"+ctx.channel().id().asLongText());
        // 添加到channelGroup 通道组
        NettyConfig.getChannelGroup().add(ctx.channel());
    }

    /**
     * 读取数据
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        log.info("服务器收到消息：{}",msg.text());

        // 获取用户ID
        JSONObject jsonObject = JSONUtil.parseObj(msg.text());
        String userId = jsonObject.getStr("userId");

        // 将用户ID作为自定义属性加入到channel中，方便随时channel中获取用户ID
        AttributeKey<String> key = AttributeKey.valueOf("userId");
        ctx.channel().attr(key).setIfAbsent(userId);

        // 关联channel
        NettyConfig.getUserChannelMap().put(userId,ctx);

        // 回复消息
        ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器连接成功！"));
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)  {
        log.info("=========读取消息==========");
        log.info("读取消息为:{}",msg);
        //DefaultFullHttpRequest(decodeResult: failure(java.lang.IllegalArgumentException: text is empty (possibly HTTP/0.9)), version: HTTP/1.0, content: UnpooledByteBufAllocator$InstrumentedUnpooledUnsafeHeapByteBuf(ridx: 0, widx: 0, cap: 0))
        //GET /bad-request HTTP/1.0
        //DefaultHttpRequest
        //FullHttpRequest
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest httpRequest = (FullHttpRequest) msg;
            if (httpRequest.content().readableBytes() > 0) {
                // 处理非空的HTTP请求
                System.out.println("Received HTTP request with content: " + httpRequest.content().toString());
            } else {
                // 处理空的HTTP请求
                System.out.println("Received empty HTTP request");
            }
        } else if (msg instanceof TextWebSocketFrame) {
            TextWebSocketFrame textWebSocketFrame = (TextWebSocketFrame) msg;
            // 处理WebSocket消息
            System.out.println("Received WebSocket message: " + textWebSocketFrame.text());
        }
        /*if(msg instanceof String){
            String data = (String) msg;
            String str = new String(data.getBytes(), CharsetUtil.UTF_8);//, CharsetUtil.UTF_8
            if("heart".equals(data)){
                //心跳

            }
            // 获取用户ID
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(msg.toString());
            String userId = jsonObject.getString("userId");
            // 将用户ID作为自定义属性加入到channel中，方便随时channel中获取用户ID
            AttributeKey<String> key = AttributeKey.valueOf("userId");
            ctx.channel().attr(key).setIfAbsent(userId);

            // 关联channel
            NettyConfig.getUserChannelMap().put(userId,ctx.channel());
            NettyConfig.getUserChannelMapClient().put("6666",ctx.channel());

        }*/
        ctx.channel().writeAndFlush("服务端收到消息后自动回复消息：hello word " + msg);


    }


    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("handlerRemoved 被调用"+ctx.channel().id().asLongText());
        // 删除通道
        NettyConfig.getChannelGroup().remove(ctx.channel());
        removeUserId(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("异常：{}",cause.getMessage());
        cause.printStackTrace();
        // 删除通道
        NettyConfig.getChannelGroup().remove(ctx.channel());
        removeUserId(ctx);
        ctx.close();
    }

    /**
     * 删除用户与channel的对应关系
     * @param ctx
     */
    private void removeUserId(ChannelHandlerContext ctx){
        AttributeKey<String> key = AttributeKey.valueOf("userId");
        String userId = ctx.channel().attr(key).get();
        if(StringUtil.isNotEmpty(userId)) {
            NettyConfig.getUserChannelMap().remove(userId);
        }

    }
}
